<template>
  <!-- 标题 -->
  <p class="title">{{ pageData.title }}</p>

  <!-- 表格 -->
  <Table ref="tableRef" :search="search" :tools="tools" :columns="columns" :api="getUser" />

  <!-- 增加模态框 -->
  <n-modal v-model:show="pageData.isShowAddModel" :mask-closable="false" preset="dialog" title="增加" positive-text="确定"
    negative-text="取消" style="width: 700px" @positive-click="add" @negative-click="addCancel"
    @after-leave="closeAddModel">
    <Form :config="addFormConfig" ref="addFormRef" />
    <div class="upload-box">
      <div class="img-box">
        <p class="name">头像</p>
        <div class="img" @click="uploadAddHeadFile">
          <n-image v-if="addHeadURL" width="95" height="95" :src="addHeadURL" lazy preview-disabled />
          <div v-else class="icon-box">
            <p class="icon-title">点击上传</p>
            <n-image width="20" height="20" :src="uploadIcon" lazy preview-disabled />
          </div>
        </div>
        <input type="file" name="" id="" class="file-input" accept="image/*" ref="addHeadInputRef"
          @change="handleAddHeadFile" />
      </div>
      <div class="img-box img-right-box">
        <p class="name">打赏码</p>
        <div class="img" @click="uploadAddCodeFile">
          <n-image v-if="addCodeURL" width="95" height="95" :src="addCodeURL" lazy preview-disabled />
          <div v-else class="icon-box">
            <p class="icon-title">点击上传</p>
            <n-image width="20" height="20" :src="uploadIcon" lazy preview-disabled />
          </div>
        </div>
        <input type="file" name="" id="" class="file-input" accept="image/*" ref="addCodeInputRef"
          @change="handleAddCodeFile" />
      </div>
    </div>

  </n-modal>

  <!-- 修改模态框 -->
  <n-modal v-model:show="pageData.isShowUpdateModel" :mask-closable="false" preset="dialog" title="编辑"
    positive-text="确定" negative-text="取消" style="width: 700px" @positive-click="update" @negative-click="updateCancel"
    @after-leave="closeUpdateModel">
    <Form ref="updateFormRef" :config="updateFormConfig" />
    <div class="upload-box" >
      <div class="img-box">
        <p class="name">头像</p>
        <div class="img" @click="uploadUpdateHeadFile">
          <n-image v-if="updateHeadURL" width="95" height="95" :src="updateHeadURL" lazy preview-disabled />
          <div v-else class="icon-box">
            <p class="icon-title">点击上传</p>
            <n-image width="20" height="20" :src="uploadIcon" lazy preview-disabled />
          </div>
        </div>
        <input type="file" name="" id="" class="file-input" accept="image/*" ref="updateHeadInputRef"
          @change="handleUpdateHeadFile" />
      </div>
      <div class="img-box img-right-box" v-show="pageData.selectedRow.is_admin !== '是'">
        <p class="name">打赏码</p>
        <div class="img" @click="uploadUpdateCodeFile">
          <n-image v-if="updateCodeURL" width="95" height="95" :src="updateCodeURL" lazy preview-disabled />
          <div v-else class="icon-box">
            <p class="icon-title">点击上传</p>
            <n-image width="20" height="20" :src="uploadIcon" lazy preview-disabled />
          </div>
        </div>
        <input type="file" name="" id="" class="file-input" accept="image/*" ref="updateCodeInputRef"
          @change="handleUpdateCodeFile" />
      </div>
    </div>
  </n-modal>

  <n-modal v-model:show="pageData.isShowAssignModel" :mask-closable="false" preset="dialog" title="分配角色"
    positive-text="确定" negative-text="取消" style="width: 700px" @positive-click="assign" @negative-click="assignCancel"
    @after-leave="closeAssignModel">
    <Form ref="assignFormRef" :config="roleFormConfig" />
  </n-modal>

</template>

<script setup lang="ts">
import { AddUser, DeleteUser, getUser, UpdateUser, getAllRole, getUserRole, deleteRole, addUserRole } from '@/api/system/user'
import { NButton, NSpace } from 'naive-ui';
import { h, reactive, ref } from 'vue';
import { addFormConfig, updateFormConfig, roleFormConfig } from './config'
import { useRoute } from 'vue-router'
import uploadIcon from "@/assets/icons/upload.png";
import { deepClone } from '@/utils/lib/clone';
import getBASE64 from '@/utils/lib/upload'
import { formatDate } from '@/utils/lib/date';

export interface IDataSource {
  tools: Record<string, any>[]
  data: Record<string, any>[]
  columns: Record<string, any>[]
  loading: boolean
  pageData: Record<string, any>[]
}

const addFormRef = ref()
const updateFormRef = ref()
const assignFormRef = ref()

const addHeadInputRef = ref()
const addCodeInputRef = ref()
const updateHeadInputRef = ref()
const updateCodeInputRef = ref()

const tableRef = ref()

const addHeadURL = ref<string>('')
const addCodeURL = ref<string>('')
const updateHeadURL = ref<string>('')
const updateCodeURL = ref<string>('')


const route = useRoute()

const closeUpdateModel = () => {
  pageData.isShowUpdateModel = false
}

const closeAddModel = () => {
  pageData.isShowAddModel = false
}

const closeAssignModel = () => {
  pageData.isShowAssignModel = false
}
/**
 * 点击触发file事件
 */
const uploadAddHeadFile = () => {
  addHeadInputRef.value.click()
}

const uploadAddCodeFile = () => {
  addCodeInputRef.value.click()
}

const uploadUpdateHeadFile = () => {
  updateHeadInputRef.value.click()

}

const uploadUpdateCodeFile = () => {
  updateCodeInputRef.value.click()

}

/**
 * 上传图片
 * @param e 事件对象
 */
const handleAddHeadFile = async (e) => {
  try {
    const file = e.target.files[0]
    if (!file) {
      return
    }
    const BASE64 = await getBASE64(file);
    addHeadURL.value = BASE64 as string;
  } catch (error) {
    return Promise.reject(error)
  }
}

const handleAddCodeFile = async (e) => {
  try {
    const file = e.target.files[0]
    if (!file) {
      return
    }
    const BASE64 = await getBASE64(file);
    addCodeURL.value = BASE64 as string;
  } catch (error) {
    return Promise.reject(error)
  }
}


const handleUpdateHeadFile = async (e) => {
  try {
    const file = e.target.files[0]
    if (!file) {
      return
    }
    const BASE64 = await getBASE64(file);
    updateHeadURL.value = BASE64 as string;
  } catch (error) {
    return Promise.reject(error)
  }
}


const handleUpdateCodeFile = async (e) => {
  try {
    const file = e.target.files[0]
    if (!file) {
      return
    }
    const BASE64 = await getBASE64(file);
    updateCodeURL.value = BASE64 as string;
  } catch (error) {
    return Promise.reject(error)
  }
}



/**
 * 增加用户
 */
const add = async () => {
  try {
    const instance = addFormRef.value.getFormRef()
    console.log(instance.model);
    instance.validate(async (err) => {
      if (!err) {
        let data = deepClone(instance.model)
        data.head = addHeadURL.value
        data.money_code = addCodeURL.value
        data.is_admin = data.is_admin === '是' ? 1 : 0
        console.log(data);

        await AddUser(data)
        tableRef.value.getData()
        addHeadURL.value = ''
        addCodeURL.value = ''
      } else {
        window['$message'].error('增加用户失败')
      }
    })
  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 更新用户信息
 */
const update = async () => {
  try {
    const instance = updateFormRef.value.getFormRef()
    // console.log(instance.model);
    instance.validate(async (err) => {
      if (!err) {
        let data = {
          ...instance.model,
          id: pageData.selectedRow.id,
          head: updateHeadURL.value,
          money_code: updateCodeURL.value
        }
        data.is_admin = data.is_admin === '是' ? 1 : 0
        console.log(data);

        await UpdateUser(data)
        tableRef.value.getData()
      } else {
        window['$message'].error('修改用户失败')
      }
    })


  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 增加弹窗取消
 */
const addCancel = () => {
  pageData.isShowAddModel = false
}

/**
 * 分配弹窗取消
 */
const assignCancel = () => {
  pageData.isShowAssignModel = false
}


/**
 * 更新弹窗取消
 */
const updateCancel = () => {
  pageData.isShowUpdateModel = false
}

const addUser = (val) => {
  console.log('add', val);
  pageData.isShowAddModel = true
}

const editUser = (row) => {
  console.log('edit', row);
  pageData.selectedRow = deepClone(row)
  updateHeadURL.value = pageData.selectedRow.head
  updateCodeURL.value = pageData.selectedRow.money_code
  pageData.isShowUpdateModel = true
  updateFormConfig.formItems.forEach(item => {
    if (item.field === 'user_id') {
      item.value = row.user_id
    }
    if (item.field === 'password') {
      item.value = row.PASSWORD
    }
    if (item.field === 'sex') {
      item.value = row.sex === '未知' ? '' : row.sex
    }
    if (item.field === 'is_admin') {

      item.value = row.is_admin
    }
    if (item.field === 'signature') {
      item.value = row.signature === '无' ? '' : row.signature
    }
    if (item.field === 'email') {
      item.value = row.email
    }
  })
}

/**
 * 删除用户信息
 */
const deleteUser = async (row) => {
  try {
    console.log('delete', row);
    window['$dialog'].success({
      title: '删除',
      content: '是否删除该条数据？',
      maskClosable: false,
      negativeText: '取消',
      positiveText: '确定',
      onPositiveClick: async () => {
        await DeleteUser({
          id: row.id
        })
        tableRef.value.getData()
      }
    })
  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 获取用户角色
 * @param user_id 用户id
 */
const getUserRoles = async (user_id: string) => {
  try {
    const data = {
      user_id
    }
    const res = await getUserRole(data)
    if (res.data.code === 200) {
      pageData.isRole = res.data.data.length > 0 ? true : false
      return Promise.resolve(res.data.data)
    }
  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 分配角色
 */
const assign = async () => {
  try {
    const instance: Record<string, any> = assignFormRef?.value?.getFormRef();
    console.log(instance.model);
    if (instance.model.roles.length === 0) {
      return
    }
    if (pageData.isRole) {
      const res = await deleteRole({
        user_id: instance.model.user_id
      })
      if (res.data.code === 200) {
        await addUserRole({
          ...instance.model
        })
      }
    } else {
      await addUserRole({
        ...instance.model
      })
    }


  } catch (error) {
    return Promise.reject(error)
  }
}

const assignRole = async (row) => {
  try {
    pageData.selectedRow = deepClone(row)
    const res = await getUserRoles(pageData.selectedRow.user_id)
    pageData.isShowAssignModel = true
    roleFormConfig.formItems.forEach(item => {
      if (item.field === 'user_id') {
        item.value = row.user_id
      }
      if (item.field === 'roles') {
        item.value = res.map(item => item.role_id)
        item.options = pageData.role.map(item => {
          return {
            label: item.role_name,
            value: item.role_id
          }
        })
      }
    })
    console.log('roleFormConfig.formItems', roleFormConfig.formItems);
  } catch (error) {
    return Promise.reject(error)
  }

}

/**
 * 搜索栏
 */
const search = [
  {
    name: '关键字搜索',
    type: 'input',
    prop: 'key',
  },
]

/**
 * 工具栏按钮
 */
const tools = [
  {
    name: ' 创建用户',
    type: 'error',
    handleClick: addUser
  }
]

/**
 * 表格
 */
const columns = [
  {
    title: '用户id',
    key: 'user_id',
    width: 100,
  },
  {
    title: '密码',
    key: 'PASSWORD',
    width: 100,
  },
  {
    title: '邮箱',
    key: 'email',
    width: 200,
  },
  {
    title: '性别',
    key: 'sex',
    width: 100,
  },
  {
    title: '个性签名',
    key: 'signature',
    width: 200,
    ellipsis: true
  },
  {
    title: '是否为管理员',
    key: 'is_admin',
    width: 150,
  },
  {
    title: '操作',
    key: 'action',
    render(row) {
      return h(NSpace, null, [
        h(NButton, {
          type: 'info',
          size: 'small',
          onClick: () => editUser(row)
        }, () => '编辑'),
        h(NButton, {
          type: 'error',
          size: 'small',
          onClick: () => deleteUser(row),

        }, () => '删除'),
        h(NButton, {
          type: 'primary',
          size: 'small',
          disabled: row.is_admin === '否',
          onClick: () => assignRole(row)
        }, () => '分配角色')
      ])
    }
  }
]


const pageData = reactive({
  selectedRow: {} as any,
  isShowAddModel: false as boolean,
  isShowUpdateModel: false as boolean,
  isShowAssignModel: false as boolean,
  title: route.meta.title as string,
  role: [] as any,
  isRole: false
})

const getRole = async () => {
  try {
    const res = await getAllRole()
    if (res.data.code === 200) {
      pageData.role = res.data.data
      console.log(pageData.role);

    }
  } catch (error) {
    return Promise.reject(error)
  }
}
getRole()



</script>

<style scoped lang="less">
@import '@/styles/mixin.less';

.title {
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 10px;
}

.upload-box {
  .flex(row, flex-start, center);

  .img-right-box {
    margin-left: 101px;
  }

  .img-box {
    .flex(row, flex-start, center);
    padding-left: 70px;

    .name {
      margin-right: 12px;

      span {
        color: #d03050;
      }
    }

    .img {
      // margin-top: 10px;
      margin-left: 10px;
      width: 100px;
      height: 100px;
      border: 2px dotted #ccc;
      background-color: rgb(250, 250, 252);
      .flex(row, center, center);
      cursor: pointer;

      p {
        font-size: 20px;
      }

      &:hover {
        border: 2px dotted green;
      }

      .icon-box {
        .flex(column, center, center);

        .icon-title {
          font-size: 14px;
          color: #666;
        }
      }
    }

    .file-input {
      display: none;
    }
  }
}
</style>